﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Classified.Data;
using Classified.Data.Repositories;
using Classified.Domain.Entities;
using Classified.Service;
using Classified.Web.Helpers;
using Classified.Web.Models;
using Classified.Web.Services;
using Classified.Web.net.webservicex.www;
using MvcPaging;

namespace Classified.Web.Controllers
{

    public class HomeController : Controller
    {

        private readonly ILocationRepository _locationRepository;
        public IFormsAuthenticationService AuthenticationService { get; set; }
        private ISecurityService _securityService { get; set; }
        private IClassifiedRepository _ClassifiedRepository { get; set; }
        private IClassifiedAdCategoryRepository _classifiedAdCategoryRepository { get; set; }
        private IOrderTypeRepositories _orderTypeRepositories { get; set; }
        private ICountryRepository _countryRepository { get; set; }
        private ITopViewRepositories _topViewRepositories { get; set; }
        private IPageRepositories _pageRepositories { get; set; }
        private IMyAccountRepositories _myAccountRepositories { get; set; }
        private IQueuedEmailRepositories _queuedEmailRepositories { get; set; }
        private IMessageInfoRepositories _messageInfoRepositories { get; set; }
        public string CategoriesId = "";
        public string CountryId = "";
        public string curlocationId = "";
        public string LocationsId = "";


        private readonly string domainName = ConfigurationManager.AppSettings["domainName"];
        private readonly string AdminEmail = ConfigurationManager.AppSettings["AdminMail"];
        private readonly ClassifiedContext DataContext = new ClassifiedContext();
        public HomeController(ILocationRepository locationRepository,
            IClassifiedAdCategoryRepository classifiedAdCategoryRepository,
            ICountryRepository countryRepository,
            ISecurityService securityService,
            IClassifiedRepository classifiedRepository,
            IOrderTypeRepositories orderTypeRepositories,
            ITopViewRepositories topViewRepositories,
            IPageRepositories pageRepositories,
            IQueuedEmailRepositories queuedEmailRepositories,
            IMyAccountRepositories myAccountRepositories,
            IMessageInfoRepositories messageInfoRepositories)
        {
            _locationRepository = locationRepository;
            _securityService = securityService;
            _ClassifiedRepository = classifiedRepository;
            _orderTypeRepositories = orderTypeRepositories;
            _countryRepository = countryRepository;
            _classifiedAdCategoryRepository = classifiedAdCategoryRepository;
            _topViewRepositories = topViewRepositories;
            _pageRepositories = pageRepositories;
            _queuedEmailRepositories = queuedEmailRepositories;
            _myAccountRepositories = myAccountRepositories;
            _messageInfoRepositories = messageInfoRepositories;
            AuthenticationService = new FormsAuthenticationService(new HttpContextWrapper(System.Web.HttpContext.Current));
        }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult PartialCheckUrl()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Check_Url()
        {
            var currentlocation = string.Empty;
            var location = string.Empty;
            var currentHost = Request.Url.Host;
            var sub = currentHost.Split('.')[0];


            if (sub == "www" || sub == domainName || sub == "mail" || sub == "krb3-pc")
            {
            }
            else
            {
                location = sub;
            }
            if (sub == "www")
            {
                location = sub;
            }

            if (!Request.IsLocal)
            {
                if (string.IsNullOrEmpty(location))
                {
                    if (location.ToLower() != "www")
                    {
                        currentlocation = GetCountry();
                        var data = _countryRepository.GetById(x => x.Name.ToLower() == currentlocation.ToLower());
                    }
                    else
                    {
                        currentlocation = "www";
                    }
                }
                else
                {
                    if (location != "www")
                    {
                        var name = location;
                        if (location.Contains("-"))
                        {
                            name = location.Replace("-", " ");
                        }

                        var data =
                            _locationRepository.GetById(
                                x => x.UrlName.ToLower() == location.ToLower() || x.Countries.Name.ToLower() == name);

                        if (data == null)
                        {

                            var country = _countryRepository.GetById(x => x.Name.ToLower() == name);
                            if (country == null)
                            {

                                currentlocation = "www";
                            }



                        }
                    }

                }
            }

            return Json(new { message = currentlocation.Replace(' ', '-') });
        }
        public string GetCountry()
        {
            var currentlocation = string.Empty;
            if (!Request.IsLocal)
            {
                var ipAddress = Request.UserHostAddress;
                var webservices = new GeoIPService();
                var currentcountry = webservices.GetGeoIP(ipAddress);
                if (currentcountry.ReturnCode == 1)
                    currentlocation = currentcountry.CountryName;
            }
            return currentlocation;
        }
        public string getLocation()
        {
            var location = string.Empty; // new Location();
            var currentHost = Request.Url.Host;
            var sub = currentHost.Split('.')[0];

            //if (!Request.IsLocal)
            //{
            if (sub == "www" || sub == domainName || sub == "mail" || sub == "krb3-pc")
            {
            }
            else
            {
                location = sub;
            }

            //}

            return location;
        }
        public ActionResult TopView()
        {
            var data = new List<ClassifiedAd>();
            GetLcationId();
            if (CountryId != "")
            {
                BuldLocationByCountryId(CountryId);
            }
            if (curlocationId != "")
            {
                BuildLocationIdPath(curlocationId);
            }
            List<TopViewCount> viewCount = DataContext.Database.SqlQuery<TopViewCount>("exec GetTopViewCount @locationId='" + LocationsId + "', @countryId='" + CountryId + "'").Where(x => x.FeaturePost == false).Take(3).ToList();
            foreach (var i in viewCount)
            {

                var calssified = _ClassifiedRepository.GetById(i.ClassifiedId);
                data.Add(calssified);
            }
            return PartialView("_PartialTopView", data);
        }
        public ActionResult Locations()
        {
            var location = new Location();
            var locationnew = getLocation();
            if (!string.IsNullOrEmpty(locationnew))
            {
                var name = locationnew;
                if (locationnew.Contains("-"))
                {
                    name = locationnew.Replace("-", " ");
                }

                var data = _locationRepository.GetById(x => x.UrlName.ToLower() == locationnew.ToLower());

                if (data == null)
                {
                    //location = _locationRepository.GetById(x => x.UrlName.ToLower() == locationnew.ToLower());
                    //if (location == null)
                    //{
                    var country = _countryRepository.GetById(x => x.Name.ToLower() == name);
                    if (country != null)
                    {
                        location = _locationRepository.GetById(x => x.CountryId == country.Id);
                        ViewBag.locationName = country.Name;
                    }

                    // }

                }
                else
                {
                    ViewBag.locationName = data.Name;
                    location = data;
                }

            }
            else
            {
                var currentlocation = GetCountry();
                location = _locationRepository.GetById(x => x.Countries.Name.ToLower() == currentlocation.ToLower());

            }





            return PartialView("Locations", location);
        }
        public PartialViewResult LocationList()
        {

            var data = new List<Location>();

            ViewBag.LocationName = string.Empty;
            var currentHost = Request.Url.Host;
            var sub = currentHost.Split('.')[0];

            if (sub == "www" || sub == domainName || sub == "mail")
            {
            }
            else
            {
                var name = sub;
                if (sub.Contains("-"))
                {
                    name = sub.Replace("-", " ");
                }
                var location = _locationRepository.GetById(x => x.UrlName.ToLower() == sub || x.Countries.Name.ToLower() == name);

                if (location != null)
                {
                    ViewBag.LocationName = location.Name;
                    ViewBag.CountryList = new SelectList(_countryRepository.GetAll(), "Id", "Name", location.CountryId);
                    data = _locationRepository.GetMany(x => x.CountryId == location.CountryId).ToList();
                }
                else
                {
                    var country = _countryRepository.GetById(x => x.Name == name);
                    ViewBag.CountryList = new SelectList(_countryRepository.GetAll(), "Id", "Name", country.Id);
                }
            }


            return PartialView("_PartialLocationList", data);
        }

        [Authorize]
        public ActionResult MyAds()
        {
            var user = AuthenticationService.GetAuthenticatedUser();
            if (user != null)
            {
                ViewBag.UserName = user.UserName;
                ViewBag.IsActive = user.IsActive;
                ViewBag.UserId = user.Id;
                var classified = _ClassifiedRepository.GetClassifiedByUserId(user.Id).ToList();
                return View(classified);
            }
            return RedirectToAction("LogOn", "Account");
        }
        public ActionResult publish()
        {
            return View();
        }
        public ActionResult OrderType()
        {
            var data = _orderTypeRepositories.GetAll();
            return PartialView(data);
        }
        public List<SelectListItem> GetParentCategories(int selectedId)
        {
            var categories = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == 0 && x.IsActive && x.Deleted == false).ToList();

            categories.Insert(0, new ClassifiedCategory { Name = "[Select Category]", Id = 0 });
            var selectList = new List<SelectListItem>();
            foreach (var c in categories)
                selectList.Add(new SelectListItem()
                {
                    Value = c.Id.ToString(),
                    Text = c.Name,
                    Selected = c.Id == selectedId
                });
            return selectList;

            //var selectList = new SelectList(categories, "Id", "Name", selectedId);
            // return new JsonResult { Data = selectList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        public ActionResult Search()
        {
            var data = new SearchModel();
            var categories = _classifiedAdCategoryRepository.GetMany(
                x => x.ParentCategoryId == 0 && x.Deleted == false).ToList();
            categories.Insert(0, new ClassifiedCategory { Name = "[Select Category]", Id = 0 });
            ViewBag.categoryId = new SelectList(categories, "Id", "Name");
            return PartialView(data);
        }
        public ActionResult SearchResult(string TextValue, int categoryId, int? page)
        {
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;


            if (categoryId != 0)
            {
                BuildCategoryIdPath(categoryId);
            }

            GetLcationId();
            if (CountryId != "")
            {
                BuldLocationByCountryId(CountryId);
            }
            if (curlocationId != "")
            {
                BuildLocationIdPath(curlocationId);
            }

            var data = _ClassifiedRepository.SearchByTextValue(TextValue, CategoriesId, LocationsId).ToPagedList(currentPageIndex, 15);

            ViewBag.CategoryName = TextValue;

            return View("SearchResult", data);
        }
        public ActionResult Page(string name)
        {
            var page = new Page();
            if (!string.IsNullOrEmpty(name))
            {
                page = _pageRepositories.GetMany(x => x.IsActive && x.Name == name).FirstOrDefault();
                if (page == null)
                    return RedirectToAction("Page");
                return View(page);
            }

            page = _pageRepositories.GetMany(x => x.IsActive && x.IsDefault).FirstOrDefault() ??
                   _pageRepositories.GetMany(x => x.IsActive).FirstOrDefault();
            return View(page);
        }

        public PartialViewResult PageList()
        {

            var data = from p in _pageRepositories.GetMany(x => x.IsActive).OrderByDescending(x => x.Name) select p.Name;
            return PartialView(data);

        }
        public ActionResult DefaultPage()
        {
            var data = _pageRepositories.GetMany(x => x.IsDefault).OrderBy(x => x.Title).Take(4).ToList();
            return PartialView(data);
        }
        public ActionResult _PartialCountry()
        {
            ViewBag.LocationName = GetCountry();

            var context = new ClassifiedContext();
            var data1 = context.LocationCount.SqlQuery("Sp_getLocations @countryName=''").ToList();
            return PartialView(data1);
        }
        public ActionResult GetAllState()
        {
            var country = GetCountry();
            //var location = _locationRepository.GetMany(x => x.Countries.Name.ToLower() == country.ToLower());
            var context = new ClassifiedContext();
            var data = context.LocationCount.SqlQuery("Sp_getLocations @countryName='" + country + "'").ToList();
            return View("_PartialAllState", data);
        }

        public ActionResult Sitemap()
        {
            var data = _classifiedAdCategoryRepository.GetMany(c => c.IsActive).OrderBy(c => c.Name);
            return View("_PartialSiteMap", data);
        }
        [OutputCache(Duration = 10)]
        public ActionResult RecentViewList()
        {
            var recentlist = new List<ClassifiedAd>();

            if (HttpContext.Request.Cookies.AllKeys.Contains("RecentView"))
            {

                HttpCookie cookie1 = HttpContext.Request.Cookies["RecentView"];
                var value = cookie1.Value.Split('|').Reverse();

                foreach (var itemid in value)
                {
                    var classifiedId = int.Parse(itemid);
                    var item = _ClassifiedRepository.GetById(x => x.Id == classifiedId);
                    recentlist.Add(item);
                }

            }
            return PartialView("_PartialRecentView", recentlist.Distinct().Take(7));
        }

        public void GetLcationId()
        {

            var name = getLocation();
            var data = _locationRepository.GetById(x => x.UrlName.ToLower() == name);
            if (data == null)
            {

                var countryname = name.Replace("-", " ");
                var countries = _countryRepository.GetById(x => x.Name.ToLower() == countryname);
                if (countries != null)
                {
                    CountryId = countries.Id.ToString();
                }
            }
            else
            {
                curlocationId = data.Id.ToString();
            }


        }
        public void BuldLocationByCountryId(string countryId)
        {
            var id = int.Parse(countryId);
            if (LocationsId == "")
            {
                LocationsId = countryId;
            }
            var location = _locationRepository.GetMany(x => x.CountryId == id);
            foreach (var i in location)
            {
                LocationsId += "," + i.Id;
                var location_id = Convert.ToString(i.Id);
                BuldLocationByCountryId(location_id);
            }
        }
        public void BuildLocationIdPath(string loc_Id)
        {
            var id = int.Parse(loc_Id);
            if (LocationsId == "")
            {
                LocationsId = loc_Id;
            }
            var location = _locationRepository.GetMany(x => x.ParentId == id);
            foreach (var i in location)
            {
                LocationsId += "," + i.Id;
                var location_id = Convert.ToString(i.Id);
                BuildLocationIdPath(location_id);
            }
        }
        public void BuildCategoryIdPath(int parentId)
        {
            if (CategoriesId == "")
            {
                CategoriesId = parentId.ToString();
            }

            var categories = _classifiedAdCategoryRepository.GetMany(x => x.ParentCategoryId == parentId);
            foreach (var category in categories)
            {
                CategoriesId += "," + category.Id;
                BuildCategoryIdPath(category.Id);
            }
        }

        public ActionResult ContactAdsx24()
        {
            var data = new MyAccount();
            return View(data);

        }
        [HttpPost]
        public ActionResult ContactAdsx24(MyAccount model)
        {
            var objQueuedEmail = new QueuedEmail();
            bool emailSendStatus = false;
            emailSendStatus = EmailHelper.SendEmail(model.Sender_EmailAddress, AdminEmail, model.Subject,
                                                    model.Body, model.Sender_FullName);


            if (!emailSendStatus)
            {
                objQueuedEmail.SentOnUtc = DateTime.UtcNow;
                objQueuedEmail.To = AdminEmail;
                objQueuedEmail.From = model.Sender_EmailAddress;
                objQueuedEmail.Body = model.Body;
                objQueuedEmail.CreatedOnUtc = DateTime.UtcNow;
                objQueuedEmail.FromName = model.Sender_FullName;
                objQueuedEmail.SentTries = 0;
                objQueuedEmail.Subject = model.Subject;
                objQueuedEmail.IsSent = false;
                _queuedEmailRepositories.Add(objQueuedEmail);
            }

            model.SentDate = DateTime.UtcNow;
            _myAccountRepositories.Add(model);
            return RedirectToAction("Index");
        }
        [Authorize]
        public ActionResult Messages(int? page)
        {
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;
            var user = AuthenticationService.GetAuthenticatedUser();
            if (user != null)
            {
                var message = _messageInfoRepositories.GetMany(x => x.UserId == user.Id).OrderByDescending(x=>x.SentDate).ToPagedList(currentPageIndex, 25);;
                return View(message);
            }
            return RedirectToAction("Index", "Home");


        }
        public ActionResult ReadMessage(int id)
        {
            var msg = _messageInfoRepositories.GetById(x => x.Id == id);
            msg.IsRead = true;
            _messageInfoRepositories.Update(msg);
            return View(msg);
        }
        [Authorize]
        public ActionResult ReplyToEmailSender(int id)
        {
            var data = _messageInfoRepositories.GetById(x => x.Id == id);
            var view = new QueuedEmail { To = data.Sender_EmailAddress, CreatedOnUtc = DateTime.UtcNow };
            return View(view);
        }
        [HttpPost]
        public ActionResult ReplyToEmailSender(QueuedEmail model)
        {
            var user = AuthenticationService.GetAuthenticatedUser();
            var objQueuedEmail = new QueuedEmail();
            bool emailSendStatus = false;
            emailSendStatus = EmailHelper.SendEmail(user.Email, model.To, model.Subject,
                                                    model.Body, user.UserName);


            if (!emailSendStatus)
            {
                objQueuedEmail.IsSent = false;
                objQueuedEmail.SentOnUtc = DateTime.UtcNow;
                objQueuedEmail.To = model.To;
                objQueuedEmail.From = user.Email;
                objQueuedEmail.Body = model.Body;
                objQueuedEmail.CreatedOnUtc = DateTime.UtcNow;
                objQueuedEmail.FromName = user.UserName;
                objQueuedEmail.SentTries = 0;
                objQueuedEmail.Subject = model.Subject;
                _queuedEmailRepositories.Add(objQueuedEmail);

            }
          var sender =  _securityService.GetUserByEmailId(model.To);
            if(sender !=null)
            {
                var msg = new MessageInfo()
                              {
                                  Body = model.Body,
                                  IsRead = false,
                                  Sender_EmailAddress = user.Email,
                                  Sender_FullName = user.UserName,
                                  SentDate = DateTime.UtcNow,
                                  Subject = model.Subject,
                                  UserId = sender.Id

                              };
                _messageInfoRepositories.Add(msg);
            }
           
            return RedirectToAction("MyAds","Home");

        }
    }
}
